package com.zjitc.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjitc.reggie.common.BaseContext;
import com.zjitc.reggie.entity.R;
import com.zjitc.reggie.entity.User;
import com.zjitc.reggie.service.UserService;
import com.zjitc.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.statement.alter.ValidateConstraint;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/add")
    public R<String> add(User user){
        userService.save(user);
        return R.success("保存成功");
    }

    @GetMapping("/get")
    public R<User> get(User user){
        Long id = BaseContext.getCurrentId();
        User service = userService.getById(id);
        return R.success(service);

    }
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            session.setAttribute(phone, code);
            log.info(code);
            return R.success("短信发送成功");
        }
        return R.error("短信发送失败");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        Object codeSession = session.getAttribute(phone);
        if (codeSession != null && codeSession.equals(code)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            //仅存储用户 ID，代码避免在会话中存储敏感数据，从而降低在发生安全漏洞时该数据被泄露的风险
            session.setAttribute("user", user.getId());
            return R.success("登录成功");
        }
        return R.error("验证码错误");
    }

    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }

}
